'''
此代码需求是生成序列号，以D,T,P或自定义开头，日期YYYYMMDD再加上两位的序列号， 每天不超过一百个

'''
import PySimpleGUI as sg
import sys
import datetime
from tinydb import TinyDB, Query
import pyperclip
import getpass

#设定操作界面，使用pysimplegui,界面的返回值为result
sg.theme('DarkAmber')   # Add a touch of color
# All the stuff inside your window.
layout = [  [sg.Text('序列码生成器')],
            [sg.Radio('D 数据订单', "RADIO1")],
            [sg.Radio("T 测试/改卡/理卡/采购", "RADIO1")],
            [sg.Radio("P 独立需求", "RADIO1")],
            [sg.Radio("其它", "RADIO1"),sg.InputText(size=(3, 1))],
            [sg.Button('确定')] ]

# Create the Window
window = sg.Window('序列码生成器', layout)
# Event Loop to process "events" and get the "values" of the inputs
while True:
    event, values = window.read()
    if values[0]:
        result='D'
    elif values[1]:
        result='T'
    elif values[2]:
        result='P'
    elif values[3]:
        result=values[4]
    #print(result)
    break
window.close()
if 'result' not in dir():
#    print('quit!')
    sys.exit()
#print(result)

#如果能查到数据， 取查到的当天的最大值，并自动加1
#如果查不到，取当天日期X100的值
username=getpass.getuser()
today=datetime.datetime.today().strftime("%Y%m%d")
now=str(datetime.datetime.today())
db = TinyDB('db0.json')
User = Query()

result0=db.search(User.date == today)
list_result=list(map(lambda x:x['num'],result0))
if list_result:
    i=max(list_result)
else:
    i=int(today)*100
i=i+1
#print('result:',result,type(result))
#print('i:',i,type(i))
code=result+str(i)
print('code:',code)
db.insert({'date': today, 'time': now,'num':i,'code':code,'username':username})
db.close()

#把值复制到剪贴板
pyperclip.copy(code)

